/*
 * drv_flash.c
 *
 *  Created on: Jun 8, 2023
 *      Author: hongwei_zhu
 */
#include "hal_flash.h"


#define FLASH_PAGE_SIZE                   256


static u8 tmp_buf[FLASH_PAGE_SIZE];


void hal_flash_read(u32 address,u8 *buf,uint16_t len)
{
   u8 *pt = (u8*)(address);
   for(int i = 0; i < len ;i++)
   {
       buf[i] = *(pt + i);
   }
}

void hal_flash_write(u32 address,u8 *buf,uint16_t len)
{
    uint32_t PageAdd;
    uint32_t secpos;
    uint16_t secoff;
    uint16_t secremain;
    uint8_t *pt_write;
    secpos = address/FLASH_PAGE_SIZE;
    secoff = address%FLASH_PAGE_SIZE;
    secremain = FLASH_PAGE_SIZE - secoff;
    pt_write = buf;

    FLASH_Unlock_Fast();
    while(len)
    {
        PageAdd = secpos * FLASH_PAGE_SIZE + 0x08000000;
        if(len <= secremain)   secremain = len;
        hal_flash_read(PageAdd,tmp_buf,256);
        memcpy(tmp_buf + secoff,pt_write,secremain);
        printf("pt_write = %d %d\r\n",pt_write[secremain-1],pt_write);
        pt_write += secremain;
        RCC->CFGR0 |= (uint32_t)RCC_HPRE_DIV2;
        FLASH_ErasePage_Fast(PageAdd);
        FLASH_ProgramPage_Fast(PageAdd,(uint32_t *)tmp_buf);
        RCC->CFGR0 &= ~(uint32_t)RCC_HPRE_DIV2;
        len -= secremain;
        secoff = 0;
        secpos ++ ;
        if(len > FLASH_PAGE_SIZE)
            secremain = FLASH_PAGE_SIZE;
        else
            secremain = len;
    }
    FLASH_Lock_Fast();

}
